Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

103
Vistas
Develop a JavaScript to Find the position of 3rd occurrence of the given string “efg” I/P:abcefgacefgabcceftyefghjklop O/p:20

I developed a logic for the above problem but i couldnt get the desired result.

    function thirdOccurence(string){
    var count = 0;
    var i=0;
    var result = 0;
    while(i<string.length){
    if(string[i]=='e' && string[i+1]=='f' && string[i+2]=='g')
    {
        count = count+1;
        i+3;
        if(count==3)
        {
                result = i+1;
                break;
        }
    }
    else
        i++;
    }     
    }*

here the string is the input - abcefgacefgabcceftyefghjklop -output should be 20 since we need to find position. I have a working code but with a different logic. But i need to know why this is not working.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The problem was with the line where you increment the i variable by 3: i += 3. This meant you jumped 3 indexes forward, before the final condition if(count==3). But if you increment i by 3 after this final condition - everything works as expected :)

function thirdOccurence(string) {
  var count = 0;
  var i = 0;
  var result = 0;
  while (i < string.length) {
    if (string[i] === "e" && string[i + 1] === "f" && string[i + 2] === "g") {
      count += 1;
      if (count === 3) {
        result = i + 1;
        break;
      }
      i += 3;
    } else {
      i++;
    }
  }
  return result
}

console.log('result should be 20:', thirdOccurence('abcefgacefgabcceftyefghjklop'))

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda